package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartService cartService;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void save(Order order) {
        //要想订单表插入，还有订单详情表两张表
        //获取当前用户
        User user = UserHolder.get();
        //查询当前用户的购物车
        List<Cart> cartServiceList = cartService.findList();
        if (CollectionUtils.isEmpty(cartServiceList)) {
            throw new CustomException("购物车数据为空，无法下单");
        }

        //根据提交的地址ID查询当前用户的收货地址，如果不存在直接返回提示
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("没有收货地址，无法下单");
        }
        //4.组装订单详情数据，保存订单详情表
        //4-1先确定下单的主键
        long orderId = IdWorker.getId();//雪花算法的plus版
        //4-2组装订单详情
        BigDecimal amount = new BigDecimal(0);//初始化金额为0
        for (Cart cart : cartServiceList) {
            OrderDetail orderDetail = new OrderDetail();//订单详情
            orderDetail.setName(cart.getName());//购物车中菜品种名称
            orderDetail.setOrderId(orderId);//提前生成的
            orderDetail.setDishId(cart.getDishId());//菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor());//菜品口味
            orderDetail.setNumber(cart.getNumber());//菜品数量
            orderDetail.setAmount(cart.getAmount());//金额
            orderDetail.setImage(cart.getImage());//图片
            //叠加金额
            //amount=amount+cart.getAmount()*cart.getNumber()
            amount = amount.add(cart.getAmount()).multiply(new BigDecimal(cart.getNumber()));
            orderDetailMapper.insert(orderDetail);
        }
        //5.组装订单数据，保存订单表
        order.setId(orderId);//这个订单的主键是我们自己定义的
        order.setNumber(String.valueOf(orderId));//订单号，自己定义
        order.setStatus(1);
        order.setUserId(user.getId());//下单用户id
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());
        order.setAmount(amount);
        order.setUserName(user.getName());
        order.setPhone(address.getPhone());
        StringBuilder sb = new StringBuilder();//拼接具体的地址
        sb.append(StringUtils.isNotEmpty(address.getProvinceName()) ? address.getProvinceName() : "");
        sb.append(StringUtils.isNotEmpty(address.getCityName()) ? address.getCityName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDistrictName()) ? address.getDistrictName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDetail()) ? address.getDetail() : "");
        order.setAddress(sb.toString());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);
        //清空购物车
        cartService.clean();
    }

    @Override
    public Page<Order> findPage(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, UserHolder.get().getId());
        wrapper.orderByDesc(Order::getOrderTime);
        //2. 构建分页条件  page
        Page<Order> page = new Page<>(pageNum, pageSize);

        //3. 执行分页查询菜品信息列表
        page = orderMapper.selectPage(page, wrapper);
        List<Order> orderList = page.getRecords();
        if (CollectionUtils.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetails);
            }
        }
        return page;
    }

    @Override
    public Page<Order> findByPage2(String number, Date beginTime, Date endTime, Integer pageNum, Integer pageSize) {
        //1. 设置分页条件
        Page<Order> page = new Page<>(pageNum, pageSize);

        //2. 设置条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(number != null, Order::getId, number);
        wrapper.ge(beginTime != null, Order::getOrderTime, beginTime);
        wrapper.le(endTime != null, Order::getOrderTime, endTime);

        //3. 设置排序(时间倒序)
        wrapper.orderByDesc(Order::getOrderTime);

        //4. 执行查询,得到订单信息
        page = orderMapper.selectPage(page, wrapper);

        //5. 遍历订单列表,得到单个订单
        List<Order> orderList = page.getRecords();
        if (CollectionUtils.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                //6. 根据订单id从详情表获取详情信息
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }

        //7. 返回
        return page;

    }

}
